import os
import tkinter as tk
import tkinter.messagebox
from tkinter import filedialog


# 获取指定目录下 所有文件
def get_template_map(file_dir, file_type):
    file_map = {}
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            splitext = os.path.splitext(file)
            if len(file_type) > 0 and splitext[1] not in file_type:
                continue
            file_map[splitext[1]] = os.path.join(root, file)

    return file_map


# 获取指定目录下 所有文件
def get_file_map(file_dir, file_type):
    file_map = {}
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            splitext = os.path.splitext(file)
            key = splitext[1]
            value = file_map.get(key)
            if len(file_type) > 0 and splitext[1] not in file_type:
                continue
            if value is None or value == 'None':
                file_map[key] = [os.path.join(root, file)]
            else:
                value.append(os.path.join(root, file))
                file_map[key] = value

    return file_map


# 获取指定目录下 指定类型的文件
def get_file_name_list(file_dir, file_type):
    file_name_list = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == ('.' + file_type):
                file_name_list.append(os.path.join(root, file))
    return file_name_list


# 打开文件多选窗口选择窗口
def open_multi_file_win(title):
    root = tk.Tk()
    root.withdraw()
    answer = filedialog.askopenfilenames(parent=root,
                                         initialdir=os.getcwd(),
                                         title=title)
    # , filetypes=file_type)
    if answer:
        root.destroy()
        return answer
    else:
        tkinter.messagebox.showinfo('提示', '没有选择文件，请重新选择')
        open_multi_file_win(title)


# 单个对话框
def show_input_dialog(title, message):
    def return_callback(event):
        # print('quit...')
        root.quit()

    def close_callback():
        tk.messagebox.showinfo('message', 'no click...')

    root = tk.Tk(className=title)
    root.wm_attributes('-topmost', 1)
    screenwidth, screenheight = root.maxsize()
    width = 800
    height = 200
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    root.geometry(size)
    root.resizable(0, 0)
    lable = tk.Label(root, height=2)
    lable['text'] = message
    lable.pack()
    entry = tk.Entry(root)
    entry.bind('<Return>', return_callback)
    entry.pack()
    entry.focus_set()
    root.protocol("WM_DELETE_WINDOW", close_callback)
    root.mainloop()
    str = entry.get()
    root.destroy()
    return str


# 打开目录
def open_dir():
    root = tk.Tk()
    root.withdraw()
    answer = filedialog.askdirectory()
    # , filetypes=file_type)
    if answer:
        root.destroy()
        return answer
    else:
        tkinter.messagebox.showinfo('提示', '没有选择路径，请重新选择')
        open_dir()
